#include<cstdio>//uncle-lu
#include<cstring>
#include<algorithm>

const int MAXT = 4001000;

int n,m;
int sum[MAXT], cnt[MAXT], F[MAXT];
int tmax;

int main()
{
	int t;
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;++i)
	{
		scanf("%d",&t);
		sum[t] += t;
		cnt[t] ++;
		tmax = std::max(tmax, t);
	}

	for(int i=1;i < tmax+m;++i) { sum[i] += sum[i-1]; cnt[i] += cnt[i-1]; }

	for(int i=0;i < tmax+m;++i)
	{
		F[i] = cnt[i] * i - sum[i];
		for(int j=std::max(i-2*m+1, 0);j <= i-m;++j)
			F[i] = std::min(F[i], F[j] + (cnt[i] - cnt[j]) * i - (sum[i] - sum[j]) );
	}

	int ans = 0x7f7f7f7;
	for(int i= tmax;i < tmax+m;++i)
	{
		ans = std::min(ans, F[i]);
	}

	printf("%d",ans);
	return 0;
}
